﻿using Microsoft.Build.Utilities;
using System;
using System.Xml;

namespace angafTasks
{
    /// <summary>
    /// Taskname: XMLModify
    /// this is my own task for manipulating xml-files
    /// example: set the loglevel after build-event to 'INFO' in the file 'SimplyBackup.exe.log4net.xml'
    /// 
    /// We want our task to do the following:
    /// 1)      Open an XML file and read the file into an XmlDocument
    /// 2)      Find the tag indicated by the property
    /// 3)      Replace the value in the tag with your value
    /// 4)      Save the Xml back out to the file
    /// 
    /// Creating a Custom Task: http://www.c-sharpcorner.com/UploadFile/mgold/MSBuildForXml07282006005222AM/MSBuildForXml.aspx
    /// <code>
    /// for use this task in project file (example: AngafSimplyBackup.vbproj), add this:
    /// 
    /// <UsingTask TaskName="angafTasks.XMLModify" AssemblyName="angafTasks"/>
    /// <Target Name="AfterBuild">
    ///     ...
    ///     <XMLModify FileName="D:\my_rechtool\kuemmel\make_backups\SimplyBackup.exe.log4net.xml" XmlXPath="//configuration/log4net/logger/level" NewValue="INFO" ModifiedAttribute="value" />
    ///     ...
    /// </Target>
    /// 
    /// </code>
    /// </summary>
    public class XMLModify : Task
    {
        private string _fileName ;public string FileName { get { return _fileName; } set { _fileName = value; } }
        private string _xmlXPath;public string XmlXPath { get { return _xmlXPath; } set { _xmlXPath = value; } }
        private string _newValue; public string NewValue { get { return _newValue; } set { _newValue = value; } }
        private string _modifiedAttribute;public string ModifiedAttribute { get { return _modifiedAttribute; } set { _modifiedAttribute = value; } }

        /* 
         * Example for modifing my log4net.xml:
         * <XMLModify FileName="D:\my_rechtool\kuemmel\make_backups\SimplyBackup.exe.log4net.xml" 
         * XmlXPath="//configuration/log4net/logger/level"
         * NewValue="INFO" 
         * ModifiedAttribute="value" 
         */
        public override bool Execute()
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(_fileName);
                //angaf: es wird immer xpath genutzt:
                XmlNode node =doc.SelectSingleNode(_xmlXPath);                
                if (node != null)                {
                    //angaf: wenn das attribute nicht existiert, wird es neu hinzugefügt:
                    if (node.Attributes[_modifiedAttribute] == null)
                    {
                      node.Attributes.Append(doc.CreateAttribute(_modifiedAttribute));
                    }
                    node.Attributes[_modifiedAttribute].Value = _newValue;
                    doc.Save(_fileName);
                    return true;
                }

                // the task failed, return false if the node doesn't exist                
                Log.LogError("Couldn't find Xml Node - {0} in file {1}", _xmlXPath,_fileName);
                return false;

            }
            catch (Exception ex)
            {
                Log.LogError(ex.Message);
            }
            
            // the task failed.
            return false;
        }
    }
}
